package whu.edu.service;


import whu.edu.Dao.SupplierRepository;
import whu.edu.Entity.Supplier;
import whu.edu.Exception.ProductException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * @author 86159
 */
@Service
public class SupplyService {

    /**
     * 将jdbc类注入
     */
    @Autowired
    SupplierRepository supplierJPARepository;

    public Supplier addSupplier(Supplier supplier) throws ProductException {
        if (supplier.getId() != null) {
            if (supplierJPARepository.findById(supplier.getId()).isPresent()) {
                throw new ProductException("添加供应商失败：供应商已经存在");
            }
        }
        return supplierJPARepository.save(supplier);
    }

    public Supplier updateSupplier(Integer id, Supplier supplier) throws ProductException {
        if (!supplierJPARepository.findById(id).isPresent()) {
            throw new ProductException("修改供应商失败：供应商"+id+"不存在");
        }
        return supplierJPARepository.saveAndFlush(supplier);
    }

    public Page<Supplier> findSuppliers(String name, Pageable pageable){
        return supplierJPARepository.findByNameContaining(name,pageable);
    }

    public Supplier getSupplier(Integer id){
        return supplierJPARepository.findById(id).get();
    }

    public void deleteSupplier(Integer id) {
        supplierJPARepository.deleteById(id);
    }


}